package datastructure.tree;

/**
 * @Description:
 * @Author Ammar
 * @Create 2023/4/5 16:36
 */
public class AVLNode<E> extends TreeNode<E> {
    public int height = 1;

    public AVLNode(E val, TreeNode<E> parent) {
        super(val, parent);
    }

    // 获取平衡因子
    public int balanceFactor() {
        int leftHeight = left == null ? 0 : ((AVLNode<E>) left).height;
        int rightHeight = right == null ? 0 : ((AVLNode<E>) right).height;
        // 左子树高度 - 右子树高度
        return leftHeight - rightHeight;
    }

    // 计算节点的高度
    public void updateHeight() {
        int leftHeight = left == null ? 0 : ((AVLNode<E>) left).height;
        int rightHeight = right == null ? 0 : ((AVLNode<E>) right).height;
        height = 1 + Math.max(leftHeight, rightHeight);
    }

    // 获取高度最高的子节点
    public TreeNode<E> tallerChild() {
        int leftHeight = left == null ? 0 : ((AVLNode<E>) left).height;
        int rightHeight = right == null ? 0 : ((AVLNode<E>) right).height;
        if (leftHeight > rightHeight) return left;
        if (leftHeight < rightHeight) return right;
        // 相等的情况下，返回跟父节点同方向的子节点
        return isLeftChild() ? left : right;
    }
}
